package com.kehutong.crm.message.service;

import java.util.List;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import com.kehutong.crm.message.entity.Message;
public class MessageTemplateTypeService {

    @Inject
    private JdbcSession jdbcSession;

   /* public Object listPage(JSONObject jsonObject) {

        return Result.success(jdbcSession.findPage(MessageTemplateType.class)
                                         .like(jsonObject, "name")
                                         .eq("deleted", false)
                                         .order("enable", "desc")
                                         .order("sort", "asc")
                                         .page(jsonObject)
                                         .exe());
    }

    public Object list(JSONObject jsonObject) {

        return Result.success(jdbcSession.findArray(MessageTemplateType.class)
                                         .eq(jsonObject, "name")
                                         .eq("deleted", false)
                                         .eq("enable", true)
                                         .order("sort", "asc")
                                         .exe());
    }

    public Object save(MessageTemplateType type) {
        jdbcSession.insert(type);

        return Result.success();
    }

    public Object update(MessageTemplateType type) {
        MessageTemplateType oldType = Pool.get(MessageTemplateType.class, type.getId());
        if (!type.getName().equals(oldType.getName())) {
            List<Message> list = jdbcSession.findArray(Message.class)
                                            .eq("classifyId", type.getId())
                                            .exe();
            list.forEach(e -> {
                e.setClassifyName(type.getName());
                jdbcSession.updateById(e);
            });
        }

        jdbcSession.updateById(type);

        return Result.success();
    }

    public Object delete(MessageTemplateType type) {
        List<Message> messageList = jdbcSession.findArray(Message.class)
                                               .eq("classifyId", type.getId())
                                               .eq("deleted", false)
                                               .exe();
        if (messageList.size() > 0) {
            return Result.error(0, "请先删除引用部分");
        }

        type.setDeleted(true);
        jdbcSession.updateById(type);

        return Result.success();
    }*/

}
